import * as fs from 'fs/promises';
import * as path from 'path';

import { contextBridge, shell, webFrame } from 'electron';
import { globalObserver, GLOBAL_EVENT } from './observer';

export function CreateElectronAPI(root: string): any {

	const API = {
		regShortCut: (cmds: { [acc: string]: Function }) => {
			(<any>document).GAME_CMDS = cmds;
			globalObserver.fire(GLOBAL_EVENT.on_game_cmd_upd);
		},
		getCWD: () => {
			return root;
		},
		exist: async (filePath: string) => {
			try {
				await fs.access(filePath);
				return true;
			} catch (err) { }
			return false;
		},
		readFile: async (filePath: string) => {
			if (!path.isAbsolute(filePath)) {
				filePath = path.join(root, filePath);
			}
			return fs.readFile(filePath);
		},
		writeFile: async (filePath: string, content: string | NodeJS.ArrayBufferView, options?: any) => {
			if (!path.isAbsolute(filePath)) {
				filePath = path.join(root, filePath);
			}
			const dir = path.dirname(filePath);
			const isExist = await API.exist(dir);
			if (!isExist) {
				await fs.mkdir(dir, { recursive: true });
			}
			return fs.writeFile(filePath, content, options);
		},
		openPath: async (filePath: string) => {
			if (!path.isAbsolute(filePath)) {
				filePath = path.join(root, filePath);
			}
			const isExist = await API.exist(filePath);
			if (!isExist) {
				alert(filePath + " not exist");
				return;
			}
			return shell.openPath(filePath);
		}
	}

	if (process.env.GAME_FREE) {
		window["electronAPI"] = API;
	} else {
		contextBridge.exposeInMainWorld('electronAPI', API);
	}
}
